from src.core.logconfig import log
from src.core.session import *
from src.entity.models import BaseModel, Message, CreateMessage, UpdateMessage
from src.common.response import success_response, fail_response
from src.utils.tools import get_cur_time
from src.common.base_router import BaseRouter
from src.common.base_service import BaseService

msg = BaseRouter(
    entity=Message,
    create_schema=CreateMessage,
    update_schema=UpdateMessage,
    out_schema=Message,
    prefix="/sys/message",
    tags=["Message"]
).router

sc = SQLCON

msg_service = BaseService(entity=Message)

async def msg_query():
    # 查询消息
    return msg_service.get_list()

async def msg_create(message: dict):
    # 创建消息
    create_data = CreateMessage(user_id=message['user_id'], username=message['username'], content=message['content'], create_time=get_cur_time())
    return msg_service.create(create=create_data)

async def msg_query(message: BaseModel):
    # 查询xx条数据，或全部
    return msg_service.get_by_id(id=message.id)

async def msg_update(message: UpdateMessage):
    # 查询消息，如果存在则更新，且可为编辑状态，则进行更新，否则不可更新
    resp = msg_service.get_by_id(id=message.id)
    if resp:
        if resp.editable:
            # 编辑消息
            update_data = UpdateMessage(id=message.id,user=message.user, content=message.content, update_time=get_cur_time())
            return msg_service.update(update=update_data)
        else:
            return fail_response("消息已被编辑，不可更新")
    return success_response("未查询到数据")
